home *** CD-ROM | disk | FTP | other *** search
/ Chip 1996 November / Chip 11-96.iso / workshop / howto / gcc < prev    next >
Text File  |  1996-09-04  |  61KB  |  1,581 lines

  1.   The Linux GCC HOWTO
  2.   Daniel Barlow <dan@detached.demon.co.uk>
  3.   v1.17, 28 February 1996
  4.  
  5.   This document covers how to set up the GNU C compiler and development
  6.   libraries under Linux, and gives an overview of compiling, linking,
  7.   running and debugging programs under it.  Most of the material in it
  8.   has been taken from Mitch D'Souza's GCC-FAQ, which it replaces, or the
  9.   ELF-HOWTO, which it will eventually largely replace.  This is the
  10.   first publically released version (despite the version number; that's
  11.   an artifact of RCS).  Feedback is welcomed.
  12.  
  13.   1.  Preliminaries
  14.  
  15.   1.1.
  16.  
  17.   ELF vs. a.out
  18.  
  19.   Linux development is in a state of flux right now.  Briefly, there are
  20.   two formats for the binaries that Linux knows how to execute, and
  21.   depending on how your system is put together, you may have either.
  22.   When reading this HOWTO, it helps to know which.
  23.  
  24.   How to tell?  Use the `file' utility (eg file /bin/bash).  For an ELF
  25.   program it will say something with ELF in, for an a.out program it
  26.   will say something involving Linux/i386.
  27.  
  28.   The differences between ELF and a.out are covered (extensively) later
  29.   in this document.  ELF is the newer format, and generally accepted as
  30.   better.
  31.  
  32.   1.2.
  33.  
  34.   Administrata
  35.  
  36.   The copyright information and like legalese can be found at the end of
  37.   this document, together with the statutory warnings about asking dumb
  38.   questions on Usenet, revealing your ignorance of the C language by
  39.   reporting bugs which aren't, and picking your nose while chewing gum.
  40.  
  41.   1.3.  Typography
  42.  
  43.   If you're reading this in Postscipt, dvi, or html format, you get to
  44.   see a little more font variation than people with the plain text
  45.   version.  In particular, filenames, commands, command output and
  46.   source code excerpts are set in some form of typewriter font, whereas
  47.   `variables' and random things that need emphasizing are empasized.
  48.  
  49.   You also get a usable index.  In dvi or postscript, the numbers in the
  50.   index are section numbers.  In HTML they're just sequentially assigned
  51.   numbers that you can click on.  In the plain text version, they really
  52.   are just numbers.  Get an upgrade!
  53.  
  54.   The Bourne (rather than C) shell syntax is used in examples.  C shell
  55.   users will want to use
  56.  
  57.        % setenv FOO bar
  58.  
  59.   where I have written
  60.  
  61.        $ FOO=bar; export FOO
  62.  
  63.   If the prompt shown is # rather than $, the command shown will
  64.   probably only work as root.  Of course, I accept no responsibility for
  65.   anything that happens to your system as a result of trying these
  66.   examples.  Have a nice day :-)
  67.  
  68.   2.  Where to get things
  69.  
  70.   2.1.  This document
  71.  
  72.   This document is one of the Linux HOWTO series, so is available from
  73.   all Linux HOWTO repositories, such as
  74.   <http://sunsite.unc.edu/pub/linux/docs/HOWTO/>.  The HTML version can
  75.   also be found (possibly in a slightly newer version) from
  76.   <http://ftp.linux.org.uk/~barlow/howto/gcc-howto.html>.
  77.  
  78.   2.2.
  79.  
  80.   Other documentation
  81.  
  82.   The official documentation for gcc is in the source distribution (see
  83.   below) as texinfo files, and as .info files.  If you have a fast
  84.   network connection, a cdrom, or a reasonable amount of patience, you
  85.   can just untar it and copy the relevant bits into /usr/info.  If not,
  86.   you may find them at tsx-11
  87.   <ftp://tsx-11.mit.edu:/pub/linux/packages/GCC/>, but not necessarily
  88.   always the latest version.
  89.  
  90.   There are two source of documentation for libc.  GNU libc comes with
  91.   info files which describe Linux libc fairly accurately except for
  92.   stdio.  Also, the manpages <ftp://sunsite.unc.edu/pub/Linux/docs/>
  93.   archive are written for Linux and describe a lot of system calls
  94.   (section 2) and libc functions (section 3).
  95.  
  96.   2.3.  GCC
  97.  
  98.   There are two answers.
  99.  
  100.   (a) The official Linux GCC distribution can always be found in binary
  101.   (ready-compiled) form at
  102.   <ftp://tsx-11.mit.edu:/pub/linux/packages/GCC/>.  At the time of
  103.   writing, 2.7.2 (gcc-2.7.2.bin.tar.gz) is the latest version.
  104.  
  105.   (b) The latest source distribution of GCC from the Free Software
  106.   Foundation can be had from GNU archives
  107.   <ftp://prep.ai.mit.edu/pub/gnu/>.  This is not necessarily always the
  108.   same version as above, though it is just now.  The Linux GCC
  109.   maintainer(s) have made it easy for you to compile the latest version
  110.   available yourself --- the configure script should set it all up for
  111.   you.  Check tsx-11 <ftp://tsx-11.mit.edu:/pub/linux/packages/GCC/> as
  112.   well, for patches which you may want to apply.
  113.  
  114.   To compile anything non-trivial (and quite a few trivial things also)
  115.   you will also need the
  116.  
  117.   2.4.
  118.  
  119.   C library and header files
  120.  
  121.   What you want here depends on (i) whether your system is ELF or a.out,
  122.   and (ii) which you want it to be.  If you're upgrading from libc 4 to
  123.   libc 5, you are recommended to look at the ELF-HOWTO from
  124.   approximately the same place as you found this document.
  125.  
  126.   These are available from tsx-11
  127.   <ftp://tsx-11.mit.edu:/pub/linux/packages/GCC/> as above:
  128.  
  129.      libc-5.2.18.bin.tar.gz
  130.         --- ELF shared library images, static libraries and include
  131.         files for the C and maths libraries.
  132.  
  133.      libc-5.2.18.tar.gz
  134.         --- Source for the above.  You will also need the .bin. package
  135.         for the header files.  If you are deliberating whether to
  136.         compile the C library yourself or use the binaries, the right
  137.         answer in nearly all cases is to use the binaries.  You will
  138.         however need to roll your own if you want NYS or shadow password
  139.         support.
  140.  
  141.      libc-4.7.5.bin.tar.gz
  142.         --- a.out shared library images and static libraries for version
  143.         4.7.5 of the C library and friends.  This is designed to coexist
  144.         with the libc 5 package above, but is only really necessary if
  145.         you wish to keep using/developing a.out format programs.
  146.  
  147.   2.5.
  148.  
  149.   Associated tools (as, ld, ar, strings etc)
  150.  
  151.   From tsx-11 <ftp://tsx-11.mit.edu:/pub/linux/packages/GCC/>, just like
  152.   everything else so far.  The current version is
  153.   binutils-2.6.0.2.bin.tar.gz.
  154.  
  155.   Note that the binutils are only available in ELF, the current libc
  156.   version is in ELF and the a.out libc is happiest when used in
  157.   conjunction with an ELF libc.  C library development is moving
  158.   emphatically ELFwards, and unless you have really good reasons for
  159.   needing a.out things you're encouraged to follow suit.
  160.  
  161.   3.  GCC installation and setup
  162.  
  163.   3.1.
  164.  
  165.   GCC versions
  166.  
  167.   You can find out what GCC version you're running by typing gcc -v at
  168.   the shell prompt.  This is also a fairly reliable way to find out
  169.   whether you are set up for ELF or a.out.  On my system it does
  170.  
  171.        $ gcc -v
  172.        Reading specs from /usr/lib/gcc-lib/i486-box-linux/2.7.2/specs
  173.        gcc version 2.7.2
  174.  
  175.   The key things to note here are
  176.  
  177.   ╖  i486.  This indicates that the gcc you are using was built for a
  178.      486 processor --- you might have 386 or 586 instead.  All of these
  179.      chips can run code compiled for each of the others; the difference
  180.      is that the 486 code has added padding in some places so runs
  181.      faster on a 486.  This has no detrimental performance effect on a
  182.      386, but does make the binaries slightly larger.
  183.  
  184.   ╖  box.  This is not at all important, and may say something else
  185.      (such as slackware or debian) or nothing at all (so that the
  186.      complete directory name is i486-linux).  If you build your own gcc,
  187.      you can set this at build time for cosmetic effect.  Just like I
  188.      did :-)
  189.  
  190.   ╖  linux.  This may instead say linuxelf or linuxaout, and,
  191.      confusingly, the meaning of each varies according to the version
  192.      that you are using.
  193.  
  194.   ╖  linux means ELF if the version is 2.7.0 or newer, a.out otherwise.
  195.  
  196.   ╖  linuxaout means a.out.  It was introduced as a target when the
  197.      definition of linux was changed from a.out to ELF, so you won't see
  198.      any linuxaout gcc older than 2.7.0.
  199.  
  200.   ╖  linuxelf is obsolete.  It is generally a version of gcc 2.6.3 set
  201.      to produce ELF executables.  Note that gcc 2.6.3 has known bugs
  202.      when producing code for ELF --- an upgrade is advisable.
  203.  
  204.   ╖  2.7.2 is the version number.
  205.  
  206.   So, in summary, I have gcc 2.7.2 producing ELF code.  Quelle surprise.
  207.  
  208.   3.2.  Where did it go?
  209.  
  210.   If you installed gcc without watching, or if you got it as part of a
  211.   distribution, you may like to find out where it lives in the
  212.   filesystem.  The key bits are
  213.  
  214.   ╖  /usr/lib/gcc-lib/target/version/ (and subdirectories) is where most
  215.      of the compiler lives.  This includes the executable programs that
  216.      do actual compiling, and some version-specific libraries and
  217.      include files.
  218.  
  219.   ╖  /usr/bin/gcc is the compiler driver --- the bit that you can
  220.      actually run from the command line.  This can be used with multiple
  221.      versions of gcc provided that you have multiple compiler
  222.      directories (as above) installed.  To find out the default version
  223.      it will use, type gcc -v.  To force it to another version, type gcc
  224.      -V version.  For example
  225.  
  226.        # gcc -v
  227.        Reading specs from /usr/lib/gcc-lib/i486-box-linux/2.7.2/specs
  228.        gcc version 2.7.2
  229.        # gcc -V 2.6.3 -v
  230.        Reading specs from /usr/lib/gcc-lib/i486-box-linux/2.6.3/specs
  231.        gcc driver version 2.7.2 executing gcc version 2.6.3
  232.  
  233.   ╖  /usr/target/(bin|lib|include)/.  If you have multiple targets
  234.      installed (for example, a.out and elf, or a cross-compiler of some
  235.      sort, the libraries, binutils (as, ld and so on) and header files
  236.      for the non-native target(s) can be found here.  Even if you only
  237.      have one kind of gcc installed you might find anyway that various
  238.      bits for it are kept here.  If not, they're in
  239.      /usr/(bin|lib|include).
  240.  
  241.   ╖  /lib/,/usr/lib and others are library directories for the native
  242.      system.  You will also need /lib/cpp for many applications (X makes
  243.      quite a lot of use of it) --- either copy it from /usr/lib/gcc-
  244.      lib/target/version/ or make a symlink pointing there.
  245.  
  246.   3.3.
  247.  
  248.   Where are the header files?
  249.  
  250.   Apart from whatever you install yourself under /usr/local/include,
  251.   there are three main sources of header files in Linux:
  252.  
  253.   ╖  Most of /usr/include/ and its subdirectories are supplied with the
  254.      libc binary package from H J Lu.  I say `most' because you may also
  255.      have files from other sources (curses and dbm libraries, for
  256.      example) in here, especially if you are using the newest libc
  257.      distribution (which doesn't come with curses or dbm, unlike the
  258.      older ones).
  259.  
  260.   ╖  /usr/include/linux and /usr/include/asm (for the files <linux/*.h>
  261.      and <asm/*.h>) should be symbolic links to the directories
  262.      linux/include/linux and linux/include/asm in the kernel source
  263.      distribution.  You need to install these if you plan to do any non-
  264.      trivial development; they are not just there for compiling the
  265.      kernel.
  266.  
  267.      You might find also that you need to do make config in the kernel
  268.      directory after unpacking the sources.  Many files depend on
  269.      <linux/autoconf.h> which otherwise may not exist, and in some
  270.      kernel versions asm is a symbolic link itself and only created at
  271.      make config time.
  272.      So, if you unpack your kernel sources under /usr/src/linux, that's
  273.  
  274.        $ cd /usr/src/linux
  275.        $ su
  276.        # make config
  277.        [answer the questions.  Unless you're going to go on and build the kernel
  278.        it doesn't matter _too_ much what you say]
  279.        # cd /usr/include
  280.        # ln -s ../src/linux/include/linux .
  281.        # ln -s ../src/linux/include/asm .
  282.  
  283.   ╖  Files such as <float.h>, <limits.h>, <varargs.h>, <stdarg.h> and
  284.      <stddef.h> vary according to the compiler version, so are found in
  285.      /usr/lib/gcc-lib/i486-box-linux/2.7.2/include/ and places of that
  286.      ilk.
  287.  
  288.   3.4.  Building cross compilers
  289.  
  290.   3.4.1.  Linux as the target platform
  291.  
  292.   Assuming you have obtained the source code to gcc, usually you can
  293.   just follow the instructions given in the INSTALL file for GCC.  A
  294.   configure --target=i486-linux --host=XXX on platform XXX followed by a
  295.   make should do the trick.  Note that you will need the Linux includes,
  296.   the kernel includes, and also to build the cross assembler and cross
  297.   linker from the sources in
  298.   <ftp://tsx-11.mit.edu/pub/linux/packages/GCC/>.
  299.  
  300.   3.4.2.  Linux as the source platform, MSDOS as the target
  301.  
  302.   Ugh.  Apparently this is somewhat possible by using the "emx" package
  303.   or the "go" extender.  Please look at
  304.   <ftp://sunsite.unc.edu/pub/Linux/devel/msdos>.
  305.  
  306.   I have not tested this and cannot vouch for its abilities.
  307.  
  308.   4.  Porting and Compiling
  309.  
  310.   4.1.
  311.  
  312.   Automatically defined symbols
  313.  
  314.   You can find out what symbols your version of gcc defines
  315.   automatically by running it with the -v switch.  For example, mine
  316.   does:
  317.  
  318.   $ echo 'main(){printf("hello world\n");}' | gcc -E -v -
  319.   Reading specs from /usr/lib/gcc-lib/i486-box-linux/2.7.2/specs
  320.   gcc version 2.7.2
  321.    /usr/lib/gcc-lib/i486-box-linux/2.7.2/cpp -lang-c -v -undef
  322.   -D__GNUC__=2 -D__GNUC_MINOR__=7 -D__ELF__ -Dunix -Di386 -Dlinux
  323.   -D__ELF__ -D__unix__ -D__i386__ -D__linux__ -D__unix -D__i386
  324.   -D__linux -Asystem(unix) -Asystem(posix) -Acpu(i386)
  325.   -Amachine(i386) -D__i486__ -
  326.  
  327.   If you are writing code that uses Linux-specific features, it is a
  328.   good idea to enclose the nonportable bits in
  329.  
  330.        #ifdef __linux__
  331.        /* ... funky stuff ... */
  332.        #endif /* linux */
  333.  
  334.   Use __linux__ for this purpose, not linux.  Although the latter is
  335.   defined, it is not POSIX compliant.
  336.  
  337.   4.2.  Compiler invocation
  338.  
  339.   The documentation for compiler switches is the gcc info page (in
  340.   Emacs, use C-h i then select the `gcc' option).  Your distributor may
  341.   not have packed this with your system, or you may have an old version;
  342.   the best thing to do in this case is to download the gcc source
  343.   archive from  <ftp://prep.ai.mit.edu/pub/gnu> or one of its mirrors,
  344.   and copy them out of it.
  345.  
  346.   The gcc manual page (gcc.1) is, generally speaking, out of date.  It
  347.   will warn you of this when you try to look at it.
  348.  
  349.   4.2.1.
  350.  
  351.   Compiler flags
  352.  
  353.   gcc can be made to optimize its output code by adding -On to its
  354.   command line, where n is an optional small integer.  Meaningful values
  355.   of n, and their exact effect, vary according to the exact version, but
  356.   typically it ranges from 0 (no optimization) to 2 (lots) or 3 (lots
  357.   and lots).
  358.  
  359.   Internally, gcc translates these to a series of -f and -m options.
  360.   You can see exactly which -O levels map to which options by running
  361.   gcc with the -v flag and the (undocumented) -Q flag.  For example, for
  362.   -O2, mine says
  363.  
  364.   enabled: -fdefer-pop -fcse-follow-jumps -fcse-skip-blocks
  365.   -fexpensive-optimizations
  366.            -fthread-jumps -fpeephole -fforce-mem -ffunction-cse -finline
  367.            -fcaller-saves -fpcc-struct-return -frerun-cse-after-loop
  368.            -fcommon -fgnu-linker -m80387 -mhard-float -mno-soft-float
  369.            -mno-386 -m486 -mieee-fp -mfp-ret-in-387
  370.  
  371.   Using an optimization level higher than your compiler supports (e.g.
  372.   -O6) will have exactly the same effect as using the highest level that
  373.   it does support.  Distributing code which is set to compile this way
  374.   is a poor idea though --- if further optimisations are incorporated
  375.   into future versions, you (or your users) may find that they break
  376.   your code.
  377.  
  378.   Users of gcc 2.7.0 thru 2.7.2 should note that there is a bug in -O2
  379.   on these.  Specifically, strength reduction doesn't work.  A patch can
  380.   be had to fix this if you feel like recompiling gcc, otherwise make
  381.   sure that you always compile with -fno-strength-reduce
  382.  
  383.   4.2.1.1.  Processor-specific
  384.  
  385.   There are other -m flags which aren't turned on by any variety of -O
  386.   but are nevertheless useful.  Chief among these are -m386 and -m486,
  387.   which tell gcc to favour the 386 or 486 respectively.  Code compiled
  388.   with one of these will still work on the other; 486 code is bigger,
  389.   but otherwise not slower on the 386.
  390.  
  391.   There is currently no -mpentium or -m586.  Linus suggests using -m486
  392.   -malign-loops=2 -malign-jumps=2 -malign-functions=2, to get 486 code
  393.   optimisations but without the big gaps for alignment (which the
  394.   pentium doesn't need).  Michael Meissner (of Cygnus) says
  395.  
  396.        My hunch is that -mno-strength-reduce also results in faster
  397.        code on the x86 (note, I'm not talking about the strength
  398.        reduction bug, which is another issue).  This is because the
  399.        x86 is rather register starved (and GCC's method of grouping
  400.        registers into spill registers vs. other registers doesn't
  401.        help either).  Strength reduction typically results in using
  402.        additional registers to replace multiplications with addi¡
  403.        tion.  I also suspect -fcaller-saves may also be a loss.
  404.  
  405.        Another hunch is that -fomit-frame-pointer might or might
  406.        not be a win.  On the one hand, it can mean that another
  407.        register is available for allocation.  On the other hand,
  408.        the way the x86 encodes its instruction set, means that
  409.        stack relative addresses take more space instead of frame
  410.        relative addresses, which means slightly less Icache avail¡
  411.        ble to the program.  Also, -fomit-frame-pointer, means that
  412.        the compiler has to constantly adjust the stack pointer
  413.        after calls, while with a frame, it can let the stack accu¡
  414.        mulate for a few calls.
  415.  
  416.   The final word on this subject is from Linus again:
  417.  
  418.   Note that if you want to get optimal performance, don't
  419.   believe me: test.  There are lots of gcc compiler switches,
  420.   and it may be that a particular set gives the best optimiza¡
  421.   tions for you.
  422.  
  423.   4.2.2.
  424.  
  425.   Internal compiler error: cc1 got fatal signal 11
  426.  
  427.   Signal 11 is SIGSEGV, or `segmentation violation'.  Usually it means
  428.   that the program got its pointers confused and tried to write to
  429.   memory it didn't own.  So, it could be a gcc bug.
  430.  
  431.   gcc is however, a well tested and reliable piece of software, for the
  432.   most part.  It also uses a large number of complex data structures,
  433.   and an awful lot of pointers.  In short, it's the pickiest RAM tester
  434.   commonly available.  If you can't duplicate the bug --- if it doesn't
  435.   stop in the same place when you restart the compilation --- it's
  436.   almost certainly a problem with your hardware (CPU, memory,
  437.   motherboard or cache).  Don't claim it as a bug because your computer
  438.   passes the power-on checks or runs Windows ok or whatever; these
  439.   `tests' are commonly and rightly held to be worthless.  And don't
  440.   claim it's a bug because a kernel compile always stops during `make
  441.   zImage' --- of course it will!  `make zImage' is probably compiling
  442.   over 200 files; we're looking for a slightly smaller place than that.
  443.  
  444.   If you can duplicate the bug, and (better) can produce a short program
  445.   that exhibits it, you can submit it as a bug report to the FSF, or to
  446.   the linux-gcc mailing list.  See the gcc documentation for details of
  447.   exactly what information they need.
  448.  
  449.   4.3.  Portability
  450.  
  451.   It has been said that, these days, if something hasn't been ported to
  452.   Linux then it is not worth having :-)
  453.  
  454.   Seriously though, in general only minor changes are needed to the
  455.   sources to get over Linux's 100% POSIX compliance. It is also
  456.   worthwhile passing back any changes to authors of the code such that
  457.   in the future only `make' need be called to provide a working
  458.   executable.
  459.  
  460.   4.3.1.  BSDisms (including bsd_ioctl, daemon and <sgtty.h>)
  461.  
  462.   You can compile your program with -I/usr/include/bsd and link it with
  463.   -lbsd (i.e. add -I/usr/include/bsd to CFLAGS and -lbsd to the LDFLAGS
  464.   line in your Makefile). There is no need to add -D__USE_BSD_SIGNAL any
  465.   more if you want BSD type signal behavior, as you get this
  466.   automatically when you have -I/usr/include/bsd and include <signal.h>.
  467.  
  468.   4.3.2.
  469.  
  470.   `Missing' signals (SIGBUS, SIGEMT, SIGIOT, SIGTRAP, SIGSYS etc)
  471.  
  472.   Linux is POSIX compliant.  These are not POSIX-defined signals ---
  473.   ISO/IEC 9945-1:1990 (IEEE Std 1003.1-1990), paragraph B.3.3.1.1 sez:
  474.  
  475.        ``The signals SIGBUS, SIGEMT, SIGIOT, SIGTRAP, and SIGSYS
  476.        were omitted from POSIX.1 because their behavior is imple¡
  477.        mentation dependent and could not be adequately categorized.
  478.        Conforming implementations may deliver these signals, but
  479.        must document the circumstances under which they are deliv¡
  480.        ered and note any restrictions concerning their delivery.''
  481.  
  482.   The cheap and cheesy way to fix this is to redefine these signals to
  483.   SIGUNUSED.  The correct way is to bracket the code that handles them
  484.   with appropriate #ifdefs:
  485.  
  486.        #ifdef SIGSYS
  487.        /* ... non-posix SIGSYS code here .... */
  488.        #endif
  489.  
  490.   4.3.3.
  491.  
  492.   K & R Code
  493.  
  494.   GCC is an ANSI compiler; much existing code is not ANSI.  There's
  495.   really not much that can be done about this, except to add
  496.   -traditional to the compiler flags.  There is a certain amount of
  497.   finer-grained control over which varieties of brain damage to emulate;
  498.   consult the gcc info page.
  499.  
  500.   Note that -traditional has effects beyond just changing the language
  501.   that gcc accepts.  For example, it turns on -fwritable-strings, which
  502.   moves string constants into data space (from text space, where they
  503.   cannot be written to).  This increases the memory footprint of the
  504.   program.
  505.  
  506.   4.3.4.
  507.  
  508.   Preprocessor symbols conflict with prototypes in the code
  509.  
  510.   One of the most frequent problems is that some common functions are
  511.   defined as macros in Linux's header files and the preprocessor will
  512.   refuse to parse similar prototype definitions in the code. Common ones
  513.   are atoi() and atol().
  514.  
  515.   4.3.5.
  516.  
  517.   sprintf()
  518.  
  519.   Something to be aware of, especially when porting from SunOS, is that
  520.   sprintf(string, fmt, ...) returns a pointer to string on many unices,
  521.   whereas Linux (following ANSI) returns the number of characters which
  522.   were put into the string.
  523.  
  524.   4.3.6.  FD_* stuff ?
  525.  
  526.   fcntl and friends.  Where are the definitions of
  527.  
  528.   In <sys/time.h>.  If you are using fcntl you probably want to include
  529.   <unistd.h> too, for the actual prototype.
  530.  
  531.   Generally speaking, the manual page for a function lists the necessary
  532.   #includes in its SYNOPSIS section.
  533.  
  534.   4.3.7.
  535.  
  536.   The select() timeout.  Programs start busy-waiting.
  537.  
  538.   Once upon a time, the timeout parameter to select() was used read-
  539.   only.  Even then, manual pages warned:
  540.  
  541.        select() should probably return the time remaining from the
  542.        original timeout, if any, by modifying the time value in
  543.        place.  This may be implemented in future versions of the
  544.        system.  Thus, it is unwise to assume that the timeout
  545.        pointer will be unmodified by the select() call.
  546.  
  547.   The future has arrived!  At least, it has here.  On return from a
  548.   select(), the timeout argument will be set to the remaining time that
  549.   it would have waited had data not arrived.  If no data had arrived,
  550.   this will be zero, and future calls using the same timeout structure
  551.   will immediately return.
  552.  
  553.   To fix, put the timeout value into that structure every time you call
  554.   select().  Change code like
  555.  
  556.              struct timeval timeout;
  557.              timeout.tv_sec = 1; timeout.tv_usec = 0;
  558.              while (some_condition)
  559.                    select(n,readfds,writefds,exceptfds,&timeout);
  560.  
  561.   to, say,
  562.  
  563.              struct timeval timeout;
  564.              while (some_condition) {
  565.                    timeout.tv_sec = 1; timeout.tv_usec = 0;
  566.                    select(n,readfds,writefds,exceptfds,&timeout);
  567.              }
  568.  
  569.   Some versions of Mosaic were at one time notable for this problem.
  570.   The speed of the spinning globe animation was inversely related to the
  571.   speed that the data was coming in from the network at!
  572.   4.3.8.
  573.  
  574.   Interrupted system calls.
  575.  
  576.   4.3.8.1.  Symptom:
  577.  
  578.   When a program is stopped using Ctrl-Z and then restarted - or in
  579.   other situations that generate signals: Ctrl-C interruption,
  580.   termination of a child process etc. - it complains about "interrupted
  581.   system call" or "write: unknown error" or things like that.
  582.  
  583.   4.3.8.2.  Problem:
  584.  
  585.   POSIX systems check for signals a bit more often than some older
  586.   unices.  Linux may execute signal handlers ---
  587.  
  588.   ╖  asynchronously (at a timer tick)
  589.  
  590.   ╖  on return from any system call
  591.  
  592.   ╖  during the execution of the following system calls: select(),
  593.      pause(), connect(), accept(), read() on terminals, sockets, pipes
  594.      or files in /proc, write() on terminals, sockets, pipes or the line
  595.      printer, open() on FIFOs, PTYs or serial lines, ioctl() on
  596.      terminals, fcntl() with command F_SETLKW, wait4(), syslog(), any
  597.      TCP or NFS operations.
  598.  
  599.   For other operating systems you may have to include the system calls
  600.   creat(), close(), getmsg(), putmsg(), msgrcv(), msgsnd(), recv(),
  601.   send(), wait(), waitpid(), wait3(), tcdrain(), sigpause(), semop() to
  602.   this list.
  603.  
  604.   If a signal (that the program has installed a handler for) occurs
  605.   during a system call, the handler is called.  When the handler returns
  606.   (to the system call) it detects that it was interrupted, and
  607.   immediately returns with -1 and errno = EINTR.  The program is not
  608.   expecting that to happen, so bottles out.
  609.  
  610.   You may choose between two fixes.
  611.  
  612.   (1) For every signal handler that you install, add SA_RESTART to the
  613.   sigaction flags. For example, change
  614.  
  615.          signal (sig_nr, my_signal_handler);
  616.  
  617.   to
  618.  
  619.     signal (sig_nr, my_signal_handler);
  620.     { struct sigaction sa;
  621.       sigaction (sig_nr, (struct sigaction *)0, &sa);
  622.   #ifdef SA_RESTART
  623.       sa.sa_flags |= SA_RESTART;
  624.   #endif
  625.   #ifdef SA_INTERRUPT
  626.       sa.sa_flags &= ~ SA_INTERRUPT;
  627.   #endif
  628.       sigaction (sig_nr, &sa, (struct sigaction *)0);
  629.     }
  630.  
  631.   Note that while this applies to most system calls, you must still
  632.   check for EINTR yourself on read(), write(), ioctl(), select(),
  633.   pause() and connect().  See below.
  634.  
  635.   (2) Check for EINTR explicitly, yourself:
  636.  
  637.   Here are two examples for read() and ioctl(),
  638.  
  639.   Original piece of code using read()
  640.  
  641.        int result;
  642.        while (len > 0) {
  643.          result = read(fd,buffer,len);
  644.          if (result < 0) break;
  645.          buffer += result; len -= result;
  646.        }
  647.  
  648.   becomes
  649.  
  650.        int result;
  651.        while (len > 0) {
  652.          result = read(fd,buffer,len);
  653.          if (result < 0) { if (errno != EINTR) break; }
  654.          else { buffer += result; len -= result; }
  655.        }
  656.  
  657.   and a piece of code using ioctl()
  658.  
  659.        int result;
  660.        result = ioctl(fd,cmd,addr);
  661.  
  662.   becomes
  663.  
  664.   int result;
  665.   do { result = ioctl(fd,cmd,addr); }
  666.   while ((result == -1) && (errno == EINTR));
  667.  
  668.   Note that in some versions of BSD Unix the default behaviour is to
  669.   restart system calls. To get system calls interrupted you have to use
  670.   the SV_INTERRUPT or SA_INTERRUPT flag.
  671.  
  672.   4.3.9.
  673.  
  674.   Writable strings (program seg faults randomly)
  675.  
  676.   GCC has an optimistic view of its users, believing that they intend
  677.   string constants to be exactly that --- constant.  Thus, it stores
  678.   them in the text (code) area of the program, where they can be paged
  679.   in and out from the program's disk image (instead of taking up
  680.   swapspace), and any attempt to rewrite them will cause a segmentation
  681.   fault.  This is a feature!
  682.  
  683.   It may cause a problem for old programs that, for example, call
  684.   mktemp() with a string constant as argument.  mktemp() attempts to
  685.   rewrite its argument in place.
  686.  
  687.   To fix, either (a) compile with -fwritable-strings, to get gcc to put
  688.   constants in data space, or (b) rewrite the offending parts to
  689.   allocate a non-constant string and strcpy the data into it before
  690.   calling.
  691.  
  692.   4.3.10.
  693.  
  694.   Why does the execl() call fail?
  695.  
  696.   Because you're calling it wrong.  The first argument to execl is the
  697.   program that you want to run.  The second and subsequent arguments
  698.   become the argv array of the program you're calling.  Remember:
  699.   argv[0] is traditionally set even when a program is run with `no'
  700.   arguments.  So, you should be writing
  701.  
  702.        execl("/bin/ls","ls",NULL);
  703.  
  704.   not just
  705.  
  706.        execl("/bin/ls", NULL);
  707.  
  708.   Executing the program with no arguments at all is construed as an
  709.   invitation to print out its dynamic library dependencies, at least
  710.   using a.out.  ELF does things differently.
  711.   (If you want this library information, there are simpler interfaces;
  712.   see the section on dynamic loading, or the manual page for ldd).
  713.  
  714.   5.  Debugging and Profiling
  715.  
  716.   5.1.
  717.  
  718.   Preventative maintenance (lint)
  719.  
  720.   There is no widely-used lint for Linux, as most people are satisfied
  721.   with the warnings that gcc can generate.  Probably the most useful is
  722.   the -Wall switch --- this stands for `Warnings, all' but probably has
  723.   more mnemonic value if thought of as the thing you bang your head
  724.   against.
  725.  
  726.   There is a public domain lint available from
  727.   <ftp://larch.lcs.mit.edu/pub/Larch/lclint>.  I don't know how good it
  728.   is.
  729.  
  730.   5.2.
  731.  
  732.   Debugging
  733.  
  734.   5.2.1.
  735.  
  736.   How do I get debugging information into a program ?
  737.  
  738.   You need to compile and link all its bits with the -g switch, and
  739.   without the -fomit-frame-pointer switch.  Actually, you don't need to
  740.   recompile all of it, just the bits you're interested in debugging.
  741.  
  742.   On a.out configurations the shared libraries are compiled with -fomit-
  743.   frame-pointer, which gdb won't get on with.  Giving the -g option when
  744.   you link should imply static linking; this is why.
  745.  
  746.   If the linker fails with a message about not finding libg.a, you don't
  747.   have /usr/lib/libg.a, which is the special debugging-enabled C
  748.   library.  It may be supplied in the libc binary package, or (in newer
  749.   C library versions) you may need to get the libc source code and build
  750.   it yourself.  You don't actually need it though; you can get enough
  751.   information for most purposes simply by symlinking it to
  752.   /usr/lib/libc.a
  753.  
  754.   5.2.1.1.
  755.  
  756.   How do I get it out again?
  757.  
  758.   A lot of GNU software comes set up to compile and link with -g,
  759.   causing it to make very big (and often static) executables.  This is
  760.   not really such a hot idea.
  761.  
  762.   If the program has an autoconf generated configure script, you can
  763.   usually turn off debugging information by doing check the Makefile.
  764.   Of course, if you're using ELF, the program is dynamically linked
  765.   regardless of the -g setting, so you can just strip it.
  766.  
  767.   5.2.2.
  768.  
  769.   Available software
  770.  
  771.   Most people use gdb, which you can get in source form from GNU archive
  772.   sites <ftp://prep.ai.mit.edu/pub/gnu>, or as a binary from tsx-11
  773.   <ftp://tsx-11.mit.edu/pub/linux/packages/GCC> or sunsite.  xxgdb is an
  774.   X debugger based on this (i.e. you need gdb installed first). The
  775.   source may be found at  <ftp://ftp.x.org/contrib/xxgdb-1.08.tar.gz>
  776.  
  777.   Also, the UPS debugger has been ported by Rick Sladkey. It runs under
  778.   X as well, but unlike xxgdb, it is not merely an X front end for a
  779.   text based debugger. It has quite a number of nice features, and if
  780.   you spend any time debugging stuff, you probably should check it out.
  781.   The Linux precompiled version and patches for the stock UPS sources
  782.   can be found in  <ftp://sunsite.unc.edu/pub/Linux/devel/debuggers/>,
  783.   and the original source at
  784.   <ftp://ftp.x.org/contrib/ups-2.45.2.tar.Z>.
  785.  
  786.   Another tool you might find useful for debugging is `strace', which
  787.   displays the system calls that a process makes.  It has a multiplicity
  788.   of other uses too, including figuring out what pathnames were compiled
  789.   into binaries that you don't have the source for, exacerbating race
  790.   conditions in programs that you suspect contain them, and generally
  791.   learning how things work.  The latest version of strace (currently
  792.   3.0.8) can be found at  <ftp://ftp.std.com/pub/jrs/>.
  793.  
  794.   5.2.3.  Background (daemon) programs
  795.  
  796.   Daemon programs typically execute fork() early, and terminate the
  797.   parent.  This makes for a short debugging session.
  798.  
  799.   The simplest way to get around this is to set a breakpoint for fork,
  800.   and when the program stops, force it to return 0.
  801.  
  802.        (gdb) list
  803.        1       #include <stdio.h>
  804.        2
  805.        3       main()
  806.        4       {
  807.        5         if(fork()==0) printf("child\n");
  808.        6         else printf("parent\n");
  809.        7       }
  810.        (gdb) break fork
  811.        Breakpoint 1 at 0x80003b8
  812.        (gdb) run
  813.        Starting program: /home/dan/src/hello/./fork
  814.        Breakpoint 1 at 0x400177c4
  815.  
  816.        Breakpoint 1, 0x400177c4 in fork ()
  817.        (gdb) return 0
  818.        Make selected stack frame return now? (y or n) y
  819.        #0  0x80004a8 in main ()
  820.            at fork.c:5
  821.        5         if(fork()==0) printf("child\n");
  822.        (gdb) next
  823.        Single stepping until exit from function fork,
  824.        which has no line number information.
  825.        child
  826.        7       }
  827.  
  828.   5.2.4.  Core files
  829.  
  830.   When Linux boots it is usually configured not to produce core files.
  831.   If you like them, use your shell's builtin command to re-enable them:
  832.   for C-shell compatibles (e.g. tcsh) this is
  833.  
  834.        % limit core unlimited
  835.  
  836.   while Bourne-like shells (sh, bash, zsh, pdksh) use
  837.  
  838.        $ ulimit -c unlimited
  839.  
  840.   If you want a bit more versatility in your core file naming (for
  841.   example, if you're trying to conduct a post-mortem using a debugger
  842.   that's buggy itself) you can make a simple mod to your kernel.  Look
  843.   for the code in fs/binfmt_aout.c and fs/binfmt_elf.c (in newer
  844.   kernels, you'll have to grep around a little in older ones) that says
  845.  
  846.                memcpy(corefile,"core.",5);
  847.        #if 0
  848.                memcpy(corefile+5,current->comm,sizeof(current->comm));
  849.        #else
  850.                corefile[4] = '\0';
  851.        #endif
  852.  
  853.   and change the 0s to 1s.
  854.  
  855.   5.3.  Profiling
  856.  
  857.   Profiling is a way to examine which bits of a program are called most
  858.   often or run for longest. It is a good way to optimize code and look
  859.   at where time is being wasted.  You must compile all object files that
  860.   you require timing information for with -p, and to make sense of the
  861.   output file you will also need gprof (from the binutils package).  See
  862.   the gprof manual page for details.
  863.  
  864.   6.  Linking
  865.  
  866.   Between the two incompatible binary formats, the static vs shared
  867.   library distinction, and the overloading of the verb `link' to mean
  868.   both `what happens after compilation' and `what happens when a
  869.   compiled program is invoked' (and, actually, the overloading of the
  870.   word `load' in a comparable but opposite sense), this section is
  871.   complicated.  Little of it is much more complicated than that
  872.   sentence, though, so don't worry too much about it.
  873.  
  874.   To alleviate the confusion somewhat, we refer to what happens at
  875.   runtime as `dynamic loading' and cover it in the next section.  You
  876.   will also see it described as `dynamic linking', but not here.  This
  877.   section, then, is exclusively concerned with the kind of linking that
  878.   happens at the end of a compilation.
  879.  
  880.   6.1.  Shared vs static libraries
  881.  
  882.   The last stage of building a program is to `link' it; to join all the
  883.   pieces of it together and see what is missing.  Obviously there are
  884.   some things that many programs will want to do --- open files, for
  885.   example, and the pieces that do these things are provided for you in
  886.   the form of libraries.  On the average Linux system these can be found
  887.   in /lib and /usr/lib/, among other places.
  888.  
  889.   When using a static library, the linker finds the bits that the
  890.   program modules need, and physically copies them into the executable
  891.   output file that it generates.  For shared libraries, it doesn't ---
  892.   instead it leaves a note in the output saying `when this program is
  893.   run, it will first have to load this library'.  Obviously shared
  894.   libraries tend to make for smaller executables; they also use less
  895.   memory and mean that less disk space is used.  The default behaviour
  896.   of Linux is to link shared if it can find the shared libraries, static
  897.   otherwise.  If you're getting static binaries when you want shared,
  898.   check that the shared library files (*.sa for a.out, *.so for ELF) are
  899.   where they should be, and are readable.
  900.  
  901.   On Linux, static libraries have names like libname.a, while shared
  902.   libraries are called libname.so.x.y.z where x.y.z is some form of
  903.   version number.  Shared libraries often also have links pointing to
  904.   them, which are important, and (on a.out configurations) associated
  905.   .sa files.  The standard libraries come in both shared and static
  906.   formats.
  907.  
  908.   You can find out what shared libraries a program requires by using ldd
  909.   (List Dynamic Dependencies)
  910.  
  911.        $ ldd /usr/bin/lynx
  912.                libncurses.so.1 => /usr/lib/libncurses.so.1.9.6
  913.                libc.so.5 => /lib/libc.so.5.2.18
  914.  
  915.   This shows that on my system the WWW browser `lynx' depends on the
  916.   presence of libc.so.5 (the C library) and libncurses.so.1 (used for
  917.   terminal control).  If a program has no dependencies, ldd will say
  918.   `statically linked' or `statically linked (ELF)'.
  919.  
  920.   6.2.
  921.  
  922.   Interrogating libraries (`which library is sin() in?')
  923.  
  924.   nm libraryname should list all the symbols that libraryname has
  925.   references to.  It works on both static and shared libraries.  Suppose
  926.   that you want to know where tcgetattr() is defined: you might do
  927.  
  928.   $ nm libncurses.so.1 |grep tcget
  929.            U tcgetattr
  930.  
  931.   The U stands for `undefined' --- it shows that the ncurses library
  932.   uses but does not define it.  You could also do
  933.  
  934.        $ nm libc.so.5 | grep tcget
  935.        00010fe8 T __tcgetattr
  936.        00010fe8 W tcgetattr
  937.        00068718 T tcgetpgrp
  938.  
  939.   The `W' stands for `weak', which means that the symbol is defined, but
  940.   in such a way that it can be overridden by another definition in a
  941.   different library.  A straightforward `normal' definition (such as the
  942.   one for tcgetpgrp) is marked by a `T'
  943.  
  944.   The short answer to the question in the title, by the way, is
  945.   libm.(so|a).  All the functions defined in <math.h> are kept in the
  946.   maths library; thus you need to link with -lm when using any of them.
  947.  
  948.   6.3.  Finding files
  949.  
  950.   ld: Output file requires shared library `libfoo.so.1`
  951.  
  952.   The file search strategy of ld and friends varies according to
  953.   version, but the only default you can reasonably assume is /usr/lib.
  954.   If you want libraries elsewhere to be searched, specify their
  955.   directories with the -L option to gcc or ld.
  956.  
  957.   If that doesn't help, check that you have the right file in that
  958.   place.  For a.out, linking with -lfoo makes ld look for libfoo.sa
  959.   (shared stubs), and if unsuccessful then for libfoo.a (static).  For
  960.   ELF, it looks for libfoo.so then libfoo.a.  libfoo.so is usually a
  961.   symbolic link to libfoo.so.x.
  962.  
  963.   6.4.  Building your own libraries
  964.  
  965.   6.4.1.  Version control
  966.  
  967.   As any other program, libraries tend to have bugs which get fixed over
  968.   time.  They also may introduce new features, change the effect of
  969.   existing ones, or remove old ones.  This could be a problem for
  970.   programs using them; what if it was depending on that old feature?
  971.  
  972.   So, we introduce library versioning.  We categorise the changes that
  973.   might be made to a library as `minor' or `major', and we rule that a
  974.   `minor' change is not allowed to break old programs that are using the
  975.   library.  You can tell the version of a library by looking at its
  976.   filename (actually, this is, strictly speaking, a lie for ELF; keep
  977.   reading to find out why) : libfoo.so.1.2 has major version 1, minor
  978.   version 2.  The minor version number can be more or less anything ---
  979.   libc puts a `patchlevel' in it, giving library names like
  980.   libc.so.5.2.18, and it's also reasonable to put letters, underscores,
  981.   or more or less any printable ASCII in it.
  982.  
  983.   One of the major differences between ELF and a.out format is in
  984.   building shared libraries.  We look at ELF first, because it's
  985.   simpler.
  986.  
  987.   6.4.2.
  988.  
  989.   ELF?  What is it then, anyway?
  990.  
  991.   ELF (Executable and Linking Format) is a binary format originally
  992.   developed by USL (UNIX System Laboratories) and currently used in
  993.   Solaris and System V Release 4.  Because of its increased flexibility
  994.   over the older a.out format that Linux was using, the GCC and C
  995.   library developers decided last year to move to using ELF as the Linux
  996.   standard binary format also.
  997.  
  998.   6.4.2.1.  Come again?
  999.  
  1000.   This section is from the document '/news-archives/comp.sys.sun.misc'.
  1001.  
  1002.        ELF ("Executable Linking Format) is the "new, improved"
  1003.        object file format introduced in SVR4. ELF is much more pow¡
  1004.        erful than straight COFF, in that it *is* user-extensible.
  1005.        ELF views an object-file as an arbitarily long list of sec¡
  1006.        tions (rather than an array of fixed size entities), these
  1007.        sections, unlike in COFF, do not HAVE to be in a certain
  1008.        place and do not HAVE to come in any specific order etc.
  1009.        Users can add new sections to object-files if they wish to
  1010.        capture new data. ELF also has a far more powerful debugging
  1011.        format called DWARF (Debugging With Attribute Record Format)
  1012.        - not currently fully supported on linux (but work is under¡
  1013.        way). A linked list of DWARF DIEs (or Debugging Information
  1014.        Entries) forms the .debug section in ELF. Instead of being a
  1015.        collection of small, fixed-size information records, DWARF
  1016.        DIEs each contain an arbitrarily long list of complex
  1017.        attributes and are written out as a scope-based tree of pro¡
  1018.        gram data. DIEs can capture a large amount of information
  1019.        that the COFF .debug section simply couldn't (like C++
  1020.        inheritance graphs etc.).
  1021.  
  1022.        ELF files are accessed via the SVR4 (Solaris 2.0 ?) ELF
  1023.        access library, which provides an easy and fast interface to
  1024.        the more gory parts of ELF. One of the major boons in using
  1025.        the ELF access library is that you will never need to look
  1026.        at an ELF file qua. UNIX file, it is accessed as an Elf *,
  1027.        after an elf_open() call and from then on, you perform
  1028.        elf_foobar() calls on its components instead of messing
  1029.        about with its actual on-disk image (something many COFFers
  1030.        did with impunity).
  1031.  
  1032.   The case for/against ELF, and the necessary contortions to upgrade an
  1033.   a.out system to support it, are covered in the ELF-HOWTO and I don't
  1034.   propose to cut/paste them here.  The HOWTO should be available in the
  1035.   same place as you found this one.
  1036.  
  1037.   6.4.2.2.  ELF shared libraries
  1038.  
  1039.   To build libfoo.so as a shared library, the basic steps look like
  1040.   this:
  1041.  
  1042.        $ gcc -fPIC -c *.c
  1043.        $ gcc -shared -Wl,-soname,libfoo.so.1 -o libfoo.so.1.0 *.o
  1044.        $ ln -s libfoo.so.1.0 libfoo.so.1
  1045.        $ ln -s libfoo.so.1 libfoo.so
  1046.        $ LD_LIBRARY_PATH=`pwd`:$LD_LIBRARY_PATH ; export LD_LIBRARY_PATH
  1047.  
  1048.   This will generate a shared library called libfoo.so.1.0, and the
  1049.   appropriate links for ld (libfoo.so) and the dynamic loader
  1050.   (libfoo.so.1) to find it.  To test, we add the current directory to
  1051.   LD_LIBRARY_PATH.
  1052.  
  1053.   When you're happpy that the library works, you'll have to move it to,
  1054.   say, /usr/local/lib, and recreate the appropriate links.  The link
  1055.   from libfoo.so.1 to libfoo.so.1.0 is kept up to date by ldconfig,
  1056.   which on most systems is run as part of the boot process.  The
  1057.   libfoo.so link must be updated manually.  If you are scrupulous about
  1058.   upgrading all the parts of a library (e.g. the header files) at the
  1059.   same time, the simplest thing to do is make libfoo.so -> libfoo.so.1,
  1060.   so that ldconfig will keep both links current for you.  If you aren't,
  1061.   you're setting yourself up to have all kinds of weird things happen at
  1062.   a later date.  Don't say you weren't warned.
  1063.  
  1064.        $ su
  1065.        # cp libfoo.so.1.0 /usr/local/lib
  1066.        # /sbin/ldconfig
  1067.        # ( cd /usr/local/lib ; ln -s libfoo.so.1 libfoo.so )
  1068.  
  1069.   6.4.2.3.
  1070.  
  1071.   Version numbering, sonames and symlinks
  1072.  
  1073.   Each library has a soname.  When the linker finds one of these in a
  1074.   library it is searching, it embeds the soname into the binary instead
  1075.   of the actual filename it is looking at.  At runtime, the dynamic
  1076.   loader will then search for a file with the name of the soname, not
  1077.   the library filename.  Thus a library called libfoo.so could have a
  1078.   soname libbar.so, and all programs linked to it would look for
  1079.   libbar.so instead when they started.
  1080.  
  1081.   This sounds like a pointless feature, but it is key to understanding
  1082.   how multiple versions of the same library can coexist on a system.
  1083.   The de facto naming standard for libraries in Linux is to call the
  1084.   library, say, libfoo.so.1.2, and give it a soname of libfoo.so.1.  If
  1085.   it's added to a `standard' library directory (e.g. /usr/lib), ldconfig
  1086.   will create a symlink libfoo.so.1 -> libfoo.so.1.2 so that the
  1087.   appropriate image is found at runtime.  You also need a link libfoo.so
  1088.   -> libfoo.so.1 so that ld will find the right soname to use at link
  1089.   time.
  1090.  
  1091.   So, when you fix bugs in the library, or add new functions (any
  1092.   changes that won't adversely affect existing programs), you rebuild
  1093.   it, keeping the soname as it was, and changing the filename.  When you
  1094.   make changes to the library that would break existing binaries, you
  1095.   simply increment the number in the soname --- in this case, call the
  1096.   new version libfoo.so.2.0, and give it a soname of libfoo.so.2.  Now
  1097.   switch the libfoo.so link to point to the new version and all's well
  1098.   with the world again.
  1099.  
  1100.   Note that you don't have to name libraries this way, but it's a good
  1101.   convention.  ELF gives you the flexibility to name libraries in ways
  1102.   that will confuse the pants off people, but that doesn't mean you have
  1103.   to use it.
  1104.  
  1105.   Executive summary: supposing that you observe the tradition that major
  1106.   upgrades may break compatibility, minor upgrades may not, then link
  1107.   with
  1108.  
  1109.        gcc -shared -Wl,-soname,libfoo.so.major -o libfoo.so.major.minor
  1110.  
  1111.   and everything will be all right.
  1112.  
  1113.   6.4.3.  a.out.  Ye olde traditional format
  1114.  
  1115.   The ease of building shared libraries is a major reason for upgrading
  1116.   to ELF.  That said, it's still possible in a.out.  Get
  1117.   <ftp://tsx-11.mit.edu/pub/linux/packages/GCC/src/tools-2.17.tar.gz>
  1118.   and read the 20 page document that you will find after unpacking it.
  1119.   I hate to be so transparently partisan, but it should be clear from
  1120.   context that I never bothered myself :-)
  1121.  
  1122.   6.4.3.1.
  1123.  
  1124.   ZMAGIC vs QMAGIC
  1125.  
  1126.   QMAGIC is an executable format just like the old a.out (also known as
  1127.   ZMAGIC) binaries, but which leaves the first page unmapped. This
  1128.   allows for easier NULL dereference trapping as no mapping exists in
  1129.   the range 0-4096. As a side effect your binaries are nominally smaller
  1130.   as well (by about 1K).
  1131.  
  1132.   Obsolescent linkers support ZMAGIC only, semi-obsolescent support both
  1133.   formats, and current versions support QMAGIC only.  This doesn't
  1134.   actually matter, though, as the kernel can still run both formats.
  1135.  
  1136.   Your `file' command should be able to identify whether a program is
  1137.   QMAGIC.
  1138.  
  1139.   6.4.3.2.  File Placement
  1140.  
  1141.   An a.out (DLL) shared library consists of two real files and a
  1142.   symlink.  For the `foo' library used throughout this document as an
  1143.   example, these files would be libfoo.sa and libfoo.so.1.2; the symlink
  1144.   would be libfoo.so.1 and would point at the latter of the files.  What
  1145.   are these for?
  1146.   At compile time, ld looks for libfoo.sa.  This is the `stub' file for
  1147.   the library, and contains all exported data and pointers to the
  1148.   functions required for run time linking.
  1149.  
  1150.   At run time, the dynamic loader looks for libfoo.so.1.  This is a
  1151.   symlink rather than a real file so that libraries can be updated with
  1152.   newer, bugfixed versions without crashing any application that was
  1153.   using the library at the time.  After the new version --- say,
  1154.   libfoo.so.1.3 --- is completely there, running ldconfig will switch
  1155.   the link to point to it in one atomic operation, leaving any program
  1156.   which had the old version still perfectly happy.
  1157.  
  1158.   DLL libraries (I know that's a tautology --- so sue me) often appear
  1159.   bigger than their static counterparts.  They reserve space for future
  1160.   expansion in the form of `holes' which can be made to take no disk
  1161.   space. A simple cp call or using the program makehole will achieve
  1162.   this.  You can also strip them after building, as the addresses are in
  1163.   fixed locations. Do not attempt to strip ELF libraries.
  1164.  
  1165.   6.4.3.3.  ``libc-lite''?
  1166.  
  1167.   A libc-lite is a light-weight version of the libc library built such
  1168.   that it will fit on a floppy and suffice for all of the most menial of
  1169.   UNIX tasks. It does not include curses, dbm, termcap etc code. If your
  1170.   /lib/libc.so.4 is linked to a lite lib, you are advised to replace it
  1171.   with a full version.
  1172.  
  1173.   6.4.4.  Linking: common problems
  1174.  
  1175.   Send me your linking problems!  I probably won't do anything about
  1176.   them, but I will write them up if I get enough ...
  1177.  
  1178.       Programs link static when you wanted them shared
  1179.  
  1180.         Check that you have the right links for ld to find each shared
  1181.         library.  For ELF this means a libfoo.so symlink to the image,
  1182.         for a.out a libfoo.sa file.  A lot of people had this problem
  1183.         after moving from ELF binutils 2.5 to 2.6 --- the earlier
  1184.         version searched more `intelligently' for shared libraries, so
  1185.         they hadn't created all the links.  The intelligent behaviour
  1186.         was removed for compatibility with other architectures, and
  1187.         because quite often it got its assumptions wrong and caused more
  1188.         trouble than it solved.
  1189.  
  1190.       The DLL tool `mkimage' fails to find libgcc, or
  1191.  
  1192.         As of libc.so.4.5.x and above, libgcc is no longer shared. Hence
  1193.         you must replace occurrences of `-lgcc' on the offending line
  1194.         with `gcc -print-libgcc-file-name` (complete with the
  1195.         backquotes).
  1196.  
  1197.         Also, delete all /usr/lib/libgcc* files.  This is important.
  1198.  
  1199.       __NEEDS_SHRLIB_libc_4 multiply defined messages
  1200.         are another consequence of the same problem.
  1201.  
  1202.       ``Assertion failure'' message when rebuilding a DLL ?
  1203.         This cryptic message most probably means that one of your jump
  1204.         table slots has overflowed because too little space has been
  1205.         reserved in the original jump.vars file.  You can locate the
  1206.         culprit(s) by running the `getsize' command provided in the
  1207.         tools-2.17.tar.gz package. Probably the only solution, though,
  1208.         is to bump the major version number of the library, forcing it
  1209.         to be backward incompatible.
  1210.  
  1211.       ld: output file needs shared library libc.so.4
  1212.         This usually happens when you are linking with libraries other
  1213.         than libc (e.g. X libraries), and use the -g switch on the link
  1214.         line without also using -static.
  1215.  
  1216.         The .sa stubs for the shared libraries usually have an undefined
  1217.         symbol _NEEDS_SHRLIB_libc_4 which gets resolved from the libc.sa
  1218.         stub.  However with -g you end up linking with libg.a or libc.a
  1219.         and thus this symbol never gets resolved, leading to the above
  1220.         error message.
  1221.  
  1222.         In conclusion, add -static when compiling with the -g flag, or
  1223.         don't link with -g.  Quite often you can get enough debugging
  1224.         information by compiling the individual files with -g, and
  1225.         linking without it.
  1226.  
  1227.   7.  Dynamic Loading
  1228.  
  1229.   This section is a tad short right now; it will be expanded over time
  1230.   as I gut the ELF howto
  1231.  
  1232.   7.1.  Concepts
  1233.  
  1234.   Linux has shared libraries, as you will by now be sick of hearing if
  1235.   you read the whole of the last section at a sitting.  Some of the
  1236.   matching-names-to-places work which was traditionally done at link
  1237.   time must be deferred to load time.
  1238.  
  1239.   7.2.  Error messages
  1240.  
  1241.   Send me your link errors!  I won't do anything about them, but I might
  1242.   write them up ...
  1243.  
  1244.       can't load library: /lib/libxxx.so, Incompatible version
  1245.         (a.out only) This means that you don't have the correct major
  1246.         version of the xxx library.  No, you can't just make a symlink
  1247.         to another version that you do have; if you are lucky this will
  1248.         cause your program to segfault.  Get the new version.  A similar
  1249.         situation with ELF will result in a message like
  1250.  
  1251.           ftp: can't load library 'libreadline.so.2'
  1252.  
  1253.      warning using incompatible library version xxx
  1254.         (a.out only) You have an older minor version of the library than
  1255.         the person who compiled the program used.  The program will
  1256.         still run.  Probably.  An upgrade wouldn't hurt, though.
  1257.  
  1258.   7.3.
  1259.  
  1260.   Controlling the operation of the dynamic loader
  1261.  
  1262.   There are a range of environment variables that the dynamic loader
  1263.   will respond to.  Most of these are more use to ldd than they are to
  1264.   the average user, and can most conveniently be set by running ldd with
  1265.   various switches.  They include
  1266.  
  1267.   ╖  LD_BIND_NOW --- normally, functions are not `looked up' in
  1268.      libraries until they are called.  Setting this flag causes all the
  1269.      lookups to happen when the library is loaded, giving a slower
  1270.      startup time.  It's useful when you want to test a program to make
  1271.      sure that everything is linked.
  1272.  
  1273.   ╖  LD_PRELOAD can be set to a file containing `overriding' function
  1274.      definitions.  For example, if you were testing memory allocation
  1275.      strategies, and wanted to replace `malloc', you could write your
  1276.      replacement routine, compile it into malloc.o and then
  1277.  
  1278.        $ LD_PRELOAD=malloc.o; export LD_PRELOAD
  1279.        $ some_test_program
  1280.  
  1281.   LD_ELF_PRELOAD and LD_AOUT_PRELOAD are similar, but only apply to the
  1282.   appropriate type of binary.  If LD_something_PRELOAD and LD_PRELOAD
  1283.   are set, the more specific one is used.
  1284.  
  1285.   ╖  LD_LIBRARY_PATH is a colon-separated list of directories in which
  1286.      to look for shared libraries.  It does not affect ld; it only has
  1287.      effect at runtime.  Also, it is disabled for programs that run
  1288.      setuid or setgid.  Again, LD_ELF_LIBRARY_PATH and
  1289.      LD_AOUT_LIBRARY_PATH can also be used to direct the search
  1290.      differently for different flavours of binary.  LD_LIBRARY_PATH
  1291.      shouldn't be necessary in normal operation; add the directories to
  1292.      /etc/ld.so.conf/ and rerun ldconfig instead.
  1293.  
  1294.   ╖  LD_NOWARN applies to a.out only.  When set (e.g. with
  1295.      LD_NOWARN=true; export LD_NOWARN) it stops the loader from issuing
  1296.      non-fatal warnings (such as minor version incompatibility
  1297.      messages).
  1298.  
  1299.   ╖  LD_WARN applies to ELF only.  When set, it turns the usually fatal
  1300.      ``Can't find library'' messages into warnings.  It's not much use
  1301.      in normal operation, but important for ldd.
  1302.  
  1303.   ╖  LD_TRACE_LOADED_OBJECTS applies to ELF only, and causes programs to
  1304.      think they're being run under ldd:
  1305.  
  1306.   $ LD_TRACE_LOADED_OBJECTS=true /usr/bin/lynx
  1307.           libncurses.so.1 => /usr/lib/libncurses.so.1.9.6
  1308.           libc.so.5 => /lib/libc.so.5.2.18
  1309.  
  1310.   7.4.
  1311.  
  1312.   Writing programs with dynamic loading
  1313.  
  1314.   This is very close to the way that Solaris 2.x dynamic loading support
  1315.   works, if you're familiar with that.  It is covered extensively in H J
  1316.   Lu's ELF programming document, and the dlopen(3) manual page, which
  1317.   can be found in the ld.so package.  Here's a nice simple example
  1318.   though: link it with -ldl
  1319.  
  1320.        #include <dlfcn.h>
  1321.        #include <stdio.h>
  1322.  
  1323.        main()
  1324.        {
  1325.          void *libc;
  1326.          void (*printf_call)();
  1327.  
  1328.          if(libc=dlopen("/lib/libc.so.5",RTLD_LAZY))
  1329.          {
  1330.            printf_call=dlsym(libc,"printf");
  1331.            (*printf_call)("hello, world\n");
  1332.          }
  1333.  
  1334.        }
  1335.  
  1336.   8.  Contacting the developers
  1337.  
  1338.   8.1.
  1339.  
  1340.   Bug reports
  1341.  
  1342.   Start by narrowing the problem down.  Is it specific to Linux, or does
  1343.   it happen with gcc on other systems?  Is it specific to the kernel
  1344.   version?  Library version?  Does it go away if you link static?  Can
  1345.   you trim the program down to something short that demonstrates the
  1346.   bug?
  1347.  
  1348.   Having done that, you'll know what program(s) the bug is in.  For GCC,
  1349.   the bug reporting procedure is explained in the info file.  For ld.so
  1350.   or the C or maths libraries, send mail to linux-gcc@vger.rutgers.edu.
  1351.   If possible, include a short and self-contained program that exhibits
  1352.   the bug, and a description both of what you want it to do, and what it
  1353.   actually does.
  1354.  
  1355.   8.2.  Helping with development
  1356.  
  1357.   If you want to help with the development effort for GCC or the C
  1358.   library, the first thing to do is join the linux-gcc@vger.rutgers.edu
  1359.   mailing list.  If you just want to see what the discussion is about,
  1360.   there are list archives at  <http://homer.ncm.com/linux-gcc/>.  The
  1361.   second and subsequent things depend on what you want to do!
  1362.  
  1363.   9.  The Remains
  1364.  
  1365.   9.1.  The Credits
  1366.  
  1367.        Only presidents, editors, and people with tapeworms have the
  1368.        right to use the editorial ``we''.
  1369.  
  1370.   (Mark Twain)
  1371.  
  1372.   This HOWTO is based very closely on Mitchum DSouza's GCC-FAQ; most of
  1373.   the information (not to mention a reasonable amount of the text) in it
  1374.   comes directly from that document.  Instances of the first person
  1375.   pronoun in this HOWTO could refer to either of us; generally the ones
  1376.   that say ``I have not tested this; don't blame me if it toasts your
  1377.   hard disk/system/spouse'' apply to both of us.
  1378.  
  1379.   Contributors to this document have included (in ASCII ordering by
  1380.   first name) Andrew Tefft, Axel Boldt, Bill Metzenthen, Bruce Evans,
  1381.   Bruno Haible, Daniel Barlow, Daniel Quinlan, David Engel, Dirk
  1382.   Hohndel, Eric Youngdale, Fergus Henderson, H.J. Lu, Jens Schweikhardt,
  1383.   Kai Petzke, Michael Meissner, Mitchum DSouza, Olaf Flebbe, Paul
  1384.   Gortmaker, Rik Faith, Steven S. Dick, Tuomas J Lukka, and of course
  1385.   Linus Torvalds, without whom the whole exercise would have been
  1386.   pointless, let alone impossible :-)
  1387.  
  1388.   Please do not feel offended if your name has not appeared here and you
  1389.   have contributed to this document (either as HOWTO or as FAQ).  Email
  1390.   me and I will rectify it.
  1391.  
  1392.   9.2.  Translations
  1393.  
  1394.   At this time, there are no known translations of this work.  If you
  1395.   wish to produce one, please go right ahead, but do tell me about it!
  1396.   The chances are (sadly) several hundred to one against that I speak
  1397.   the language you wish to translate to, but that aside I am happy to
  1398.   help in whatever way I can.
  1399.  
  1400.   9.3.  is welcomed.  Mail me at dan@detached.demon.co.uk.  My PGP pub¡
  1401.   lic key (ID 5F263625) is available from my web pages
  1402.   <http://ftp.linux.org.uk/~barlow/>, if you feel the need to be secre¡
  1403.   tive about things.  Feedback
  1404.  
  1405.   9.4.  Legalese
  1406.  
  1407.   All trademarks used in this document are acknowledged as being owned
  1408.   by their respective owners.
  1409.  
  1410.   This document is copyright (C) 1996 Daniel Barlow
  1411.   <dan@detached.demon.co.uk> It may be reproduced and distributed in
  1412.   whole or in part, in any medium physical or electronic, as long as
  1413.   this copyright notice is retained on all copies. Commercial
  1414.   redistribution is allowed and encouraged; however, the author would
  1415.   like to be notified of any such distributions.
  1416.  
  1417.   All translations, derivative works, or aggregate works incorporating
  1418.   any Linux HOWTO documents must be covered under this copyright notice.
  1419.   That is, you may not produce a derivative work from a HOWTO and impose
  1420.   additional restrictions on its distribution. Exceptions to these rules
  1421.   may be granted under certain conditions; please contact the Linux
  1422.   HOWTO coordinator at the address given below.
  1423.  
  1424.   In short, we wish to promote dissemination of this information through
  1425.   as many channels as possible. However, we do wish to retain copyright
  1426.   on the HOWTO documents, and would like to be notified of any plans to
  1427.   redistribute the HOWTOs.
  1428.  
  1429.   If you have questions, please contact Greg Hankins, the Linux HOWTO
  1430.   coordinator, at gregh@sunsite.unc.edu via email.
  1431.  
  1432.   10.  Index
  1433.  
  1434.   Entries starting with a non-alphabetical character are listed in ASCII
  1435.   order.
  1436.  
  1437.   ╖  -fwritable-strings ``39'' ``56''
  1438.  
  1439.   ╖  /lib/cpp ``16''
  1440.  
  1441.   ╖  a.out ``1''
  1442.  
  1443.   ╖  ar ``10''
  1444.  
  1445.   ╖  as ``8''
  1446.  
  1447.   ╖  <asm/*.h> ``19''
  1448.  
  1449.   ╖  atoi() ``40''
  1450.  
  1451.   ╖  atol() ``41''
  1452.  
  1453.   ╖  binaries too big ``63'' ``65'' ``77''
  1454.  
  1455.   ╖  chewing gum ``3''
  1456.  
  1457.   ╖  cos() ``68''
  1458.  
  1459.   ╖  debugging ``59''
  1460.  
  1461.   ╖  dlopen() ``82''
  1462.  
  1463.   ╖  dlsym() ``83''
  1464.  
  1465.   ╖  documentation ``4''
  1466.  
  1467.   ╖  EINTR ``52''
  1468.  
  1469.   ╖  elf ``0'' ``71''
  1470.  
  1471.   ╖  execl() ``57''
  1472.  
  1473.   ╖  fcntl ``47''
  1474.  
  1475.   ╖  FD_CLR ``44''
  1476.  
  1477.   ╖  FD_ISSET ``45''
  1478.  
  1479.   ╖  FD_SET ``43''
  1480.  
  1481.   ╖  FD_ZERO ``46''
  1482.  
  1483.   ╖  file ``2''
  1484.  
  1485.   ╖  <float.h> ``20''
  1486.  
  1487.   ╖  gcc ``6''
  1488.  
  1489.   ╖  gcc -fomit-frame-pointer ``61''
  1490.  
  1491.   ╖  gcc -g ``60''
  1492.  
  1493.   ╖  gcc -v ``14''
  1494.  
  1495.   ╖  gcc, bugs ``15'' ``28'' ``29'' ``84''
  1496.  
  1497.   ╖  gcc, flags ``13'' ``25'' ``26''
  1498.  
  1499.   ╖  gdb ``64''
  1500.  
  1501.   ╖  header files ``17''
  1502.  
  1503.   ╖  interrupted system calls ``51''
  1504.  
  1505.   ╖  ld ``9''
  1506.  
  1507.   ╖  LD_* environment variables ``80''
  1508.  
  1509.   ╖  ldd ``81''
  1510.  
  1511.   ╖  libc ``7''
  1512.  
  1513.   ╖  libg.a ``62''
  1514.  
  1515.   ╖  libgcc ``79''
  1516.  
  1517.   ╖  <limits.h> ``21''
  1518.  
  1519.   ╖  lint ``58''
  1520.  
  1521.   ╖  <linux/*.h> ``18''
  1522.  
  1523.   ╖  manual pages ``5''
  1524.  
  1525.   ╖  <math.h> ``70''
  1526.  
  1527.   ╖  maths ``69''
  1528.  
  1529.   ╖  mktemp() ``55''
  1530.  
  1531.   ╖  optimisation ``27''
  1532.  
  1533.   ╖  QMAGIC ``76''
  1534.  
  1535.   ╖  segmentation fault ``30'' ``54''
  1536.  
  1537.   ╖  segmentation fault, in GCC ``33''
  1538.  
  1539.   ╖  select() ``50''
  1540.  
  1541.   ╖  SIGBUS ``34''
  1542.  
  1543.   ╖  SIGEMT ``35''
  1544.  
  1545.   ╖  SIGIOT ``36''
  1546.  
  1547.   ╖  SIGSEGV ``31'' ``53''
  1548.  
  1549.   ╖  SIGSEGV, in gcc ``32''
  1550.  
  1551.   ╖  SIGSYS ``38''
  1552.  
  1553.   ╖  SIGTRAP ``37''
  1554.  
  1555.   ╖  sin() ``67''
  1556.  
  1557.   ╖  soname ``73''
  1558.  
  1559.   ╖  sprintf() ``42''
  1560.  
  1561.   ╖  statically linked binaries, unexpected ``66'' ``78''
  1562.  
  1563.   ╖  <stdarg.h> ``23''
  1564.  
  1565.   ╖  <stddef.h> ``24''
  1566.  
  1567.   ╖  strings ``11''
  1568.  
  1569.   ╖  <sys/time.h> ``48''
  1570.  
  1571.   ╖  <unistd.h> ``49''
  1572.  
  1573.   ╖  <varargs.h> ``22''
  1574.  
  1575.   ╖  version numbers ``12'' ``74''
  1576.  
  1577.   ╖  weird things ``72''
  1578.  
  1579.   ╖  ZMAGIC ``75''
  1580.  
  1581.